package com.example.gatewayservice.Service;


import com.example.gatewayservice.constants.ActivityConstants;
import com.example.gatewayservice.constants.RoleConstants;
import com.example.gatewayservice.domain.UserActivityMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;

import java.util.Arrays;

@Slf4j
public class Activity {

    private static RabbitTemplate rabbitTemplate;

    public static void recordUserActivity(String userId, String role, String path, ServerHttpRequest request) {
        // 构建活跃度消息
        UserActivityMessage message = new UserActivityMessage(
                userId,
                role,
                path,
                getMethodValue(path),
                System.currentTimeMillis(),
                request.getHeaders().getFirst("User-Agent")
        );

        // 根据角色发送到不同的路由键（也可以使用相同交换机和队列，在消费者中区分）
        String routingKey = ActivityConstants.Filter_ROUTING_KEY_PREF + role.toLowerCase();

        // 发送到RabbitMQ
        rabbitTemplate.convertAndSend(
//                "user.activity.exchange",
                ActivityConstants.USER_ACTIVITY_EXCHANGE,
                routingKey,
                message
        );
    }

    public static String getMethodValue(String path) {
        // 步骤 1：去掉协议和主机部分，获取路径
        int firstSlashIndex = path.indexOf('/');
        String pathPart = (firstSlashIndex != -1) ? path.substring(firstSlashIndex) : "";

        // 步骤 2：按 '/' 分割路径
        String[] segments = pathPart.split("/");

        // 步骤 3：提取第1、2个非空段
        String part1 = null;
        String part2 = null;

        int count = 0;
        for (String seg : segments) {
            if (seg.isEmpty()) continue;
            if (count == 0) part1 = seg;
            else if (count == 1) part2 = seg;
            count++;
        }
        if (part1 == null) return null;

        if (!Arrays.asList(RoleConstants.STUDENT, RoleConstants.TEACHER).contains(part1)) {
            log.error("用户访问的模块不存在,是否存在如下用户？？？网关过滤器" + part1);
            return null;
        }
        return part2;
    }


}
